package com.lik888.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        //获取response的输出流
        PrintWriter writer = response.getWriter();
        writer.write("{" +
                "\"code\":403," +
                "\"msg\":\"权限不足，无法访问：" + accessDeniedException.getMessage() + "\"," + // 加逗号分隔
                "\"success\":false" + // 布尔值不加引号
                "}");
        writer.flush();
        writer.close();
    }
}
